﻿using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using Android.Locations;
using HeWeatherAPI;
using HeWeatherAPI.Model;
using Weather.Adapter;
using Java.Lang;

namespace Weather
{
    [Activity(Label = "Weather", MainLauncher = true, Icon = "@drawable/icon")]
    public class MainActivity : Activity
    {
        private HeWeather weather;
        private string searchText;
        ProgressDialog dialog;
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            var button = this.FindViewById<Button>(Resource.Id.SearchButton);

            button.Click += (o, e) =>
            {

                var txtSearch = this.FindViewById<EditText>(Resource.Id.SearchText);
                this.searchText = txtSearch.Text;

                this.GetData();
            };
        }

        private void GetData()
        {
            dialog = ProgressDialog.Show(this, "Waiting...", "Search weather for " + this.searchText, true, false);
            new Thread(() =>
            {
                this.RunOnUiThread(() =>
                {
                    this.Binding();
                });

            }).Start();
        }

        private void Binding()
        {
            var result = HeWeatherClient.Instance.Query(this.searchText);

            if (result != HeWeatherResult.Error)
            {
                this.weather = result.Weather[0];

                var hourlyList = this.FindViewById<ListView>(Resource.Id.HourlyForcast);
                var hourlyAdapter = new HourlyAdapter(this, weather.HourlyForcasts);
                hourlyList.Adapter = hourlyAdapter;

                var dailyList = this.FindViewById<ListView>(Resource.Id.DailyForcast);
                var dailyAdapter = new DailyAdapter(this, weather.DailyForcasts);
                dailyList.Adapter = dailyAdapter;

                var nowPanel = this.FindViewById<LinearLayout>(Resource.Id.NowPanel);

                var currentAdapter = new CurrentAdapter(this, weather.Current);
                currentAdapter.BindTo(nowPanel);
            }

            if (dialog != null)
            {
                dialog.Dismiss();
            }
        }

        protected override void OnResume()
        {
            base.OnResume();
            this.GetData();
        }
    }
}

